package com.woosiyuan.atie.demo;

import android.graphics.PixelFormat;
import android.media.MediaRecorder;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.TextView;
import com.woosiyuan.atierobot.utils.BaseActivity;
import com.woosiyuan.wsyrobotdemo.R;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;

public class RecordActivity extends BaseActivity {
    private Button        start;
    private SurfaceView   mSurfaceView;
    private MediaRecorder mMediaRecorder;
    private SurfaceHolder mSurfaceHolder;
    private File          mRecVideoPath;
    private File          mRecAudioFile;
    private TextView      timer;
    private int hour   = 0;
    private int minute = 0;
    private int second = 0;
    private   boolean  bool;
    protected boolean  isPreview;
    private boolean isRecording = true; // true表示没有录像，点击开始；false表示正在录像
    private String path = "";

    @Override protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
            /*
             * 全屏显示
             */
        this.requestWindowFeature(Window.FEATURE_NO_TITLE);
        this.getWindow()
            .setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
                    WindowManager.LayoutParams.FLAG_FULLSCREEN);
        getWindow().setFormat(PixelFormat.TRANSLUCENT);
        setContentView(R.layout.activity_cameras);

        timer = (TextView) findViewById(R.id.video_timer);
        start = (Button) findViewById(R.id.start_video);
        mSurfaceView = (SurfaceView) this.findViewById(R.id.video_view);

        // 设置计时器不可见
        timer.setVisibility(View.GONE);

        // 设置缓存路径
        mRecVideoPath = new File(Environment.getExternalStorageDirectory().getAbsolutePath() +
                "/hfdatabase/video/temp/");
        if (!mRecVideoPath.exists()) {
            mRecVideoPath.mkdirs();
        }

        // 绑定预览视图
        SurfaceHolder holder = mSurfaceView.getHolder();
        holder.addCallback(new SurfaceHolder.Callback() {

            @Override public void surfaceDestroyed(SurfaceHolder holder) {
                mSurfaceView = null;
                mSurfaceHolder = null;
                mMediaRecorder = null;
            }

            @Override public void surfaceCreated(SurfaceHolder holder) {
                mSurfaceHolder = holder;
            }

            @Override
            public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
                mSurfaceHolder = holder;
            }
        });
        holder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);

        start.setOnClickListener(new Button.OnClickListener() {

            @Override public void onClick(View v) {
                showMsg("开始录制");
                doVideoRecording("/sdcard/wsy_test/photo");
            }
        });
        final Button stop = (Button) findViewById(R.id.stop_video);
        stop.setOnClickListener(new View.OnClickListener() {

            @Override public void onClick(View v) {
                stopVideoRecording();
            }
        });
    }

    public void stopVideoRecording(){
        if (mMediaRecorder != null) {
            try {
                bool = false;
                mMediaRecorder.stop();
                timer.setText(format(hour) + ":" + format(minute) + ":" + format(second));
                mMediaRecorder.release();
                mMediaRecorder = null;
                videoRename();
            } catch (Exception e) {
                e.printStackTrace();
            }
            isRecording = !isRecording;
            showMsg("录制完成，已保存");
            finish();
        }
    }
    /*
     * 点击开始录像
     */
    public void doVideoRecording(String path){
        if (isRecording) {
            second = 0;
            minute = 0;
            hour = 0;
            bool = true;
            this.path = path;
            if (mMediaRecorder == null) {
                mMediaRecorder = new MediaRecorder();
            } else {
                mMediaRecorder.reset();
            }
            mMediaRecorder.setPreviewDisplay(mSurfaceHolder.getSurface());
            mMediaRecorder.setVideoSource(MediaRecorder.VideoSource.CAMERA);
            mMediaRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
            mMediaRecorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
            mMediaRecorder.setVideoEncoder(MediaRecorder.VideoEncoder.H264);
            mMediaRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
            mMediaRecorder.setVideoSize(320, 240);
            mMediaRecorder.setVideoFrameRate(15);
            try {
                mRecAudioFile = File.createTempFile("Vedio", ".3gp", mRecVideoPath);
            } catch (IOException e) {
                e.printStackTrace();
            }
            mMediaRecorder.setOutputFile(mRecAudioFile.getAbsolutePath());
            try {
                mMediaRecorder.prepare();
                timer.setVisibility(View.VISIBLE);
                handler.postDelayed(task, 1000);
                mMediaRecorder.start();
            } catch (Exception e) {
                e.printStackTrace();
            }
            showMsg("开始录制");
            isRecording = !isRecording;
        }
    }


    /*
     * 生成video文件名字
     */
    protected void videoRename() {
        if(path.equals(""))return;
        String fileName = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date()) + ".3gp";
        File out = new File(path);
        if (!out.exists()) {
            out.mkdirs();
        }
        out = new File(path, fileName);
        if (mRecAudioFile.exists()) {
            mRecAudioFile.renameTo(out);
        }
    }

    /*
     * 定时器设置，实现计时
     */
    private Handler  handler = new Handler();
    private Runnable task    = new Runnable() {
        public void run() {
            if (bool) {
                handler.postDelayed(this, 1000);
                second++;
                if (second >= 60) {
                    minute++;
                    second = second % 60;
                }
                if (minute >= 60) {
                    hour++;
                    minute = minute % 60;
                }
                timer.setText(format(hour) + ":" + format(minute) + ":" + format(second));
            }
        }
    };


    /*
     * 格式化时间
     */
    public String format(int i) {
        String s = i + "";
        if (s.length() == 1) {
            s = "0" + s;
        }
        return s;
    }

    /*
     * 覆写返回键监听
     */
    @Override public void onBackPressed() {
        if (mMediaRecorder != null) {
            mMediaRecorder.stop();
            mMediaRecorder.release();
            mMediaRecorder = null;
            videoRename();
        }
        finish();
    }

    @Override protected void onPause() {
        super.onPause();
        onBackPressed();
    }
}

